# coding = utf-8
# @Author: Lemongman

import logging
from threading import Lock


class LogHandler:
    __instance_lock = Lock()

    # 清空历史日志
    try:
        with open('.log.txt', 'wb') as f:
            f.truncate()
    except Exception as e:
        print(e)

    def __new__(cls, *args, **kwargs):
        with LogHandler.__instance_lock:
            if not hasattr(LogHandler, '_instance'):
                LogHandler._instance = object.__new__(cls)
                return LogHandler._instance

    def __init__(self):
        self.logger = self.init_structure()

    @staticmethod
    def init_structure():
        fmt = '[%(levelname)s][%(asctime)s]: %(message)s'
        datefmt = '%m-%d %H:%M:%S'
        formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)

        logger = logging.getLogger('allog')
        logger.setLevel(logging.INFO)
        # 添加文件处理器
        file_handler = logging.FileHandler('logs/log.txt')
        # 设置文件输出格式
        file_handler.setFormatter(fmt=formatter)

        # 添加控制台处理器
        console_handler = logging.StreamHandler()
        # 设置控制台输出格式
        console_handler.setFormatter(fmt=formatter)

        # 日志过滤器
        def pass_log(record):
            if record.name == 'NoneType: None':
                return False
            return True

        filter_handler = logging.Filter()
        filter_handler.filter = pass_log

        # 添加处理器
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)
        logger.addFilter(filter_handler)
        return logger

    def debug(self, text):
        return self.logger.debug(text, exc_info=True)

    def info(self, text):
        return self.logger.info(text, exc_info=True)

    def warning(self, text):
        return self.logger.warning(text, exc_info=True)

    def error(self, text):
        return self.logger.error(text, exc_info=True)


logger = LogHandler()
